// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })
  const db = cloud.database()
  const wxContext = cloud.getWXContext()

  app.router("getTags", async (ctx, next) => {
    const res = await db.collection("tags").get()
      ctx.body = {
        code: 200,
        data: res.data
      }
  })

  app.router("updateTags", async (ctx, next) => {
    const res = await db.collection('users')
      .where({
        _openid: wxContext.OPENID
      })
      .get()
      if(res.data[0].role === "admin"){
        const r = await db.collection("tags").update({
          data: {
            lists: event.lists
          }
        })
        ctx.body = {
          code: 200
        }
      } else {
        ctx.body = {
          code: 403
        }
      }
    
  })

  return app.serve()
}